package com.gexiaobao.pigeon.ui.fragment.personal

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.blankj.utilcode.util.ThreadUtils.runOnUiThread
import com.flyjingfish.openimagelib.OpenImage
import com.flyjingfish.openimagelib.enums.MediaType
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.Constant
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.model.bean.QueryBalanceResponse
import com.gexiaobao.pigeon.app.model.bean.UserInfoResponse
import com.gexiaobao.pigeon.app.network.HttpUtil
import com.gexiaobao.pigeon.app.util.CacheUtil
import com.gexiaobao.pigeon.app.util.ImageLoaderManager
import com.gexiaobao.pigeon.app.util.KvUtils
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.SettingUtil
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.databinding.FragmentPersonalCenterBinding
import com.gexiaobao.pigeon.ui.activity.TestInputActivity
import com.gexiaobao.pigeon.ui.adapter.HotGoodsAdapter
import com.gexiaobao.pigeon.ui.auction.ActivityAuctionAllOrder
import com.gexiaobao.pigeon.ui.auction.ActivityAuctionFollow
import com.gexiaobao.pigeon.ui.auction.ActivityMarginPayment
import com.gexiaobao.pigeon.ui.auction.ActivityMyPartAuction
import com.gexiaobao.pigeon.ui.dialog.RxDialogBigImage
import com.gexiaobao.pigeon.ui.mall.MallViewModel
import com.gexiaobao.pigeon.viewmodel.request.RequestHomeViewModel
import com.google.zxing.BarcodeFormat
import com.google.zxing.WriterException
import com.google.zxing.qrcode.QRCodeWriter
import com.luck.picture.lib.thread.PictureThreadUtils
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.LogUtils
import me.hgj.jetpackmvvm.util.startActivity
import org.json.JSONException
import org.json.JSONObject

/**
 * @Author      : hxw
 * @Date        : 2024/12/23 13:31
 * @Describe    : 我的（个人中心）
 */
class MineShopHomePage : BaseFragment<MallViewModel, FragmentPersonalCenterBinding>() {

    private var headerView: View? = null
    private var isHideBalance: Boolean = true
    private var isHideMargin: Boolean = true
    private var totalPriceStr: String = ""
    private var totalGebiStr: String = ""
    private var mQueryBalance: QueryBalanceResponse? = null
    private val mHotAdapter: HotGoodsAdapter by lazy { HotGoodsAdapter(arrayListOf()) }
    private var channelID = ""
    private var iconUrl = ""
    private var remainMoney = ""
    private var totalFreezeMoney = ""
//    private var bitmap: Bitmap? = null

    //请求数据ViewModel
    private val requestHomeViewModel: RequestHomeViewModel by viewModels()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
    }

    override fun initView(savedInstanceState: Bundle?) {
//        val userId = KvUtils.decodeString(Constant.USERID)
//        generateQRCode(userId) // 生成二维码并显示
        /** 正在热卖 */
        val layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        mDatabind.swipeRecyclerView.init(layoutManager, mHotAdapter)
        mDatabind.swipeRecyclerView.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
                super.getItemOffsets(outRect, view, parent, state)
                outRect.right = Util.dp2px(context, 5f)//右间距5dp
                outRect.left = Util.dp2px(context, 5f)//左间距5dp
                outRect.top = Util.dp2px(context, 5f)//上间距5dp
                outRect.bottom = Util.dp2px(context, 5f)//下间距5dp
            }
        })

        mDatabind.swipeRefreshLayout.init {
            requestHomeViewModel.getUserDetail()
            mViewModel.getTotalFreezeMoney()
        }

        headerView = LayoutInflater.from(context).inflate(R.layout.header_layout_hot_goods, null)
        mHotAdapter.setHeaderView(headerView!!)

        eventViewModel.toNoticeBackHome.observeInFragment(this) {
            activity?.let { StatusBarUtil.setLightMode(it) }
            activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
        }

        eventViewModel.toRefreshData.observeInFragment(this) {
            mViewModel.getTotalFreezeMoney()
            mViewModel.queryBalance()
        }

        showLoading(getString(R.string.loading))
        mViewModel.getTotalFreezeMoney()

        eventViewModel.addShopCarResult.observeInFragment(this) {
            lazyLoadData()
        }

        val userData = CacheUtil.getUser()
        refreshUserInfo(userData)

        eventViewModel.refundReturnResult.observeInFragment(this) {
            if (it) {
                mViewModel.queryBalance()
            }
        }
        eventViewModel.shopCarEmptyResult.observeInFragment(this) {
            mDatabind.marketMainCarNum.visibility = View.GONE
        }

        mHotAdapter.setOnItemClickListener { _, _, position ->
            nav().navigateAction(R.id.action_to_fragment_goods_detail, Bundle().apply {
                putString("id", mHotAdapter.data[position].goodsId.toString())
            })
        }
        val isRecommend = KvUtils.decodeBooleanTure(Constant.IS_RECOMMENDATION, true)
        mDatabind.llRecommend.isVisible = isRecommend
    }

    private fun refreshUserInfo(userData: UserInfoResponse?) {
        if (userData != null) {
            mDatabind.userData = userData
            iconUrl = userData.iconUrl
            ImageLoaderManager.loadCircleImageFall(context, iconUrl, mDatabind.ivMallHeadIcon, R.mipmap.head_default_icon)
        }
    }

//    private fun generateQRCode(userId: String) {
//        if (userId.isEmpty()) {
//            LogUtils.warnInfo("UserId为空")
//            return
//        }
//        val qrCodeWriter = QRCodeWriter()
//        try {
//            val bitMatrix = qrCodeWriter.encode(userId, BarcodeFormat.QR_CODE, 240, 240)
//            val width = bitMatrix.width
//            val height = bitMatrix.height
//            bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
//
//            val canvas = Canvas(bitmap!!)
//            canvas.drawColor(Color.WHITE)
//
//            val paint = Paint()
//            paint.isAntiAlias = true
//            paint.isFilterBitmap = true
//            paint.isDither = true
//
//            for (x in 0 until width) {
//                for (y in 0 until height) {
//                    bitmap!!.setPixel(x, y, if (bitMatrix[x, y]) Color.BLACK else Color.WHITE)
//                }
//            }
//        } catch (e: WriterException) {
//            e.printStackTrace()
//        }
//    }

    override fun onResume() {
        super.onResume()
        getNotifyTotal()
    }

    /** 获取用户未读数量 */
    private fun getNotifyTotal() {
        Thread {
            HttpUtil.getInstance().getImNotifyList { total ->
                runOnUiThread {
                    mDatabind.dragPointViewNotice.text = if (total >= 100) "99+" else total.toString()
                    mDatabind.dragPointViewNotice.isVisible = total != 0
                }
            }
        }.start()
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        mViewModel.getHotSaleList()
        mViewModel.getShopCartCnt()
        mViewModel.queryBalance()
        mViewModel.getPlatFormId()
    }

    @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        requestHomeViewModel.run {
            /** 用户数据 */
            userInfoResult.observe(viewLifecycleOwner) {
                if (mDatabind.swipeRefreshLayout.isRefreshing) {
                    mDatabind.swipeRefreshLayout.isRefreshing = false
                }
                refreshUserInfo(it)
            }
        }
        /** 获取保证金信息 */
        mViewModel.freezeMoneyResult.observe(viewLifecycleOwner) {
            remainMoney = it.remainMoney.toString()
            totalFreezeMoney = it.totalFreezeMoney.toString()
            isHideMargin = KvUtils.decodeBooleanTure(Constant.IS_MARGIN_BALANCE_HIDE, true)
            if (isHideMargin) {
                mDatabind.tvMarginBalance.setContent("***")
                mDatabind.tvAllMyMargin.text = "***"
                mDatabind.ivMyMarginBalance.setImageResource(R.mipmap.icon_mine_balance_hide)
            } else {
                mDatabind.tvMarginBalance.setContent(remainMoney)
                mDatabind.tvAllMyMargin.text = totalFreezeMoney
                mDatabind.ivMyMarginBalance.setImageResource(R.mipmap.icon_mine_balance_show)
            }
        }
        /** 获取平台id */
        mViewModel.platformIDResult.observe(viewLifecycleOwner) {
            channelID = if (it.id == 0) "" else it.id.toString()
        }
        /** 获取热卖商品列表 */
        mViewModel.HotGoodsListResult.observe(viewLifecycleOwner) {
            if (it.isEmpty()) {
                if (headerView != null) {
                    headerView!!.isVisible = false
                }
                return@observe
            }
            headerView!!.isVisible = true
            mHotAdapter.setList(it.list)
            mHotAdapter.notifyDataSetChanged()
        }
        /** 查询余额 */
        mViewModel.queryBalanceResult.observe(viewLifecycleOwner) { resultState ->
            parseState(resultState, {
                mQueryBalance = it
                totalGebiStr = it.gebiCnt.toString()
                totalPriceStr = Util.makeDoubleToThousandNo(SettingUtil.div(it.allAmount - it.freezenAmount, 100.00, 2)).toString()
                isHideBalance = KvUtils.decodeBooleanTure(Constant.IS_BALANCE_HIDE, true)
                if (isHideBalance) {
                    mDatabind.tvMallCanUserBalance.setContent("***")//✱✱✱
                    mDatabind.tvShoppingPigeonCoin.text = "***"
                    mDatabind.ivMallCanUserBalance.setImageResource(R.mipmap.icon_mine_balance_hide)
                } else {
                    mDatabind.tvMallCanUserBalance.setContent(totalPriceStr)
                    mDatabind.tvShoppingPigeonCoin.text = totalGebiStr
                    mDatabind.ivMallCanUserBalance.setImageResource(R.mipmap.icon_mine_balance_show)
                }
            }, {
                RxToast.showToast(it.msg)
            })
        }
        mViewModel.carCountResult.observe(viewLifecycleOwner) {
            mDatabind.data = it
        }
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.marketShopCar,
            mDatabind.marketShopOrder,
            mDatabind.llCollect,
            mDatabind.llOnlineService,
            mDatabind.mallHomeNoPay,
            mDatabind.mallHomeNoReceived,
            mDatabind.MallHomeNoEvaluate,
            mDatabind.MallHomeAfterSales,
            mDatabind.llMineStore,
            mDatabind.tvToRecharge,
            mDatabind.llMinePigeonRank,
            mDatabind.ivMallCanUserBalance,
            mDatabind.ivPersonalCenterBack,
            mDatabind.ivPersonalSetting,
            mDatabind.RlNotice,
            mDatabind.ivMallHeadIcon,
            mDatabind.llAuctionAllOrder,
            mDatabind.llAuctionFollow,
            mDatabind.llAuctionParticipation,
            mDatabind.ivMyMarginBalance,
            mDatabind.tvToRechargeMargin,
            mDatabind.llQrcode
        ) {
            when (it) {
//                mDatabind.llQrcode -> showBigImageDialog(bitmap)
                mDatabind.tvToRechargeMargin -> startActivity<ActivityMarginPayment>()
                mDatabind.ivMyMarginBalance -> {
                    if (isHideMargin) {
                        mDatabind.tvMarginBalance.setContent(remainMoney)
                        mDatabind.tvAllMyMargin.setContent(totalFreezeMoney)
                        mDatabind.ivMyMarginBalance.setImageResource(R.mipmap.icon_mine_balance_show)
                    } else {
                        mDatabind.tvMarginBalance.setContent("***")
                        mDatabind.tvAllMyMargin.setContent("***")
                        mDatabind.ivMyMarginBalance.setImageResource(R.mipmap.icon_mine_balance_hide)
                    }
                    isHideMargin = !isHideMargin
                    KvUtils.encode(Constant.IS_MARGIN_BALANCE_HIDE, isHideMargin)
                }

                mDatabind.llAuctionParticipation -> startActivity<ActivityMyPartAuction>()
                mDatabind.llAuctionFollow -> startActivity<ActivityAuctionFollow>()
                mDatabind.llAuctionAllOrder -> startActivity<ActivityAuctionAllOrder>()
                mDatabind.ivMallHeadIcon -> openImage()
                mDatabind.ivPersonalCenterBack -> nav().navigateUp()
                mDatabind.llMineStore -> nav().navigateAction(R.id.action_to_fragment_mine_store)
                mDatabind.MallHomeAfterSales -> nav().navigateAction(R.id.action_to_fragment_after_sales)
                mDatabind.MallHomeNoEvaluate -> nav().navigateAction(R.id.action_to_fragment_evaluate_list)
                mDatabind.mallHomeNoReceived -> nav().navigateAction(R.id.action_to_fragment_mine_order, Bundle().apply {
                    putInt("orderIndex", 2)
                })

                mDatabind.mallHomeNoPay -> nav().navigateAction(R.id.action_to_fragment_mine_order, Bundle().apply {
                    putInt("orderIndex", 1)
                })

                mDatabind.llOnlineService -> chatLogin()
                mDatabind.llCollect -> nav().navigateAction(R.id.action_to_fragment_collect_goods_list)
                mDatabind.marketShopOrder -> nav().navigateAction(R.id.action_to_fragment_mine_order, Bundle().apply {
                    putInt("orderIndex", 0)
                })

                mDatabind.marketShopCar -> nav().navigateAction(R.id.action_to_fragment_shop_car)
                mDatabind.tvToRecharge -> {
                    val isCertified = KvUtils.decodeBoolean("isCertified")
                    if (isCertified) {
                        nav().navigateAction(R.id.action_to_account_recharge)
                    } else {
                        nav().navigateAction(R.id.action_to_account_setting_process, Bundle().apply {
                            putString(Constant.INTO_TYPE, "mine")
                        })
                    }
                }

                mDatabind.llMinePigeonRank -> nav().navigateAction(R.id.action_to_fragment_pigeon_ranking)
                mDatabind.ivMallCanUserBalance -> {
                    if (isHideBalance) {
                        mDatabind.tvMallCanUserBalance.setContent(totalPriceStr)
                        mDatabind.tvShoppingPigeonCoin.setContent(totalGebiStr)
                        mDatabind.ivMallCanUserBalance.setImageResource(R.mipmap.icon_mine_balance_show)
                    } else {
                        mDatabind.tvMallCanUserBalance.setContent("***")
                        mDatabind.tvShoppingPigeonCoin.setContent("***")
                        mDatabind.ivMallCanUserBalance.setImageResource(R.mipmap.icon_mine_balance_hide)
                    }
                    isHideBalance = !isHideBalance
                    KvUtils.encode(Constant.IS_BALANCE_HIDE, isHideBalance)
                }

                mDatabind.ivPersonalSetting -> nav().navigateAction(R.id.action_to_setting)
                mDatabind.RlNotice -> nav().navigateAction(R.id.action_to_shop_notice)

            }
        }
    }

//    private fun showBigImageDialog(bitmap: Bitmap?) {
//        val dialog = RxDialogBigImage(context)
//        if (bitmap != null) {
//            dialog.setImage(bitmap)
//        }
//        dialog.setFullScreen()
//        dialog.show()
//    }

    private fun openImage() {
        OpenImage.with(context)
            .setClickImageView(mDatabind.ivMallHeadIcon)
            .setSrcImageViewScaleType(ImageView.ScaleType.CENTER_CROP, true)
            .setImageUrl(iconUrl, MediaType.IMAGE).show()
    }

    private fun chatLogin() {
        val uid = KvUtils.decodeString(Constant.USERID)
        val token = CacheUtil.getToken()
        if (!TextUtils.isEmpty(uid) && !TextUtils.isEmpty(token)) {
            val jsonObject = JSONObject()
            try {
                jsonObject.put("uid", uid)
                jsonObject.put("token", token)
                jsonObject.put("device_flag", 0)
                jsonObject.put("device_level", 1)
            } catch (e: JSONException) {
                throw RuntimeException(e)
            }
            Thread {
                HttpUtil.getInstance().post("/user/token", jsonObject) { code, _ ->
                    if (code == 200) {
                        LogUtils.debugInfo("FragmentPersonalCenter:登录成功")
                        startActivity<TestInputActivity>("channelId" to channelID, "token" to token, "uid" to uid, "isService" to true)
                    } else {
                        PictureThreadUtils.runOnUiThread {
                            RxToast.showToast("登录失败【$code】")
                        }
                    }
                }
            }.start()
        }
    }

}